import createError from 'http-errors'
import express from 'express'
import path from 'path'
import cookieParser from 'cookie-parser'
import logger from 'morgan'

// 使 express 能够捕获手动抛出的异步错误
import 'express-async-errors'
// 引入路由中间价
import indexRouter from '../controller/index'
import usersRouter from '../controller/user'
import uploadRouter from '../controller/load'
import tagRouter from '../controller/tag'
import blogRouter from '../controller/blog'
import { defaultErrorHandler, parseTokenHandler, requestUrl, sessionHandler } from './app.middleware'

// 创建服务器实例.
const app = express();

// 注册各种中间件
app.use(sessionHandler)
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(parseTokenHandler)

// 注册路由
app.use(requestUrl)
app.use('/api', indexRouter);
app.use('/api/admin', usersRouter);
app.use('/api/load', uploadRouter);
app.use('/api/tag', tagRouter);
app.use('/api/blog', blogRouter);

// 注册错误处理中间件
app.use(function(req, res, next) {
  next(createError(404));
});

// 错误处理
app.use(defaultErrorHandler);

export default app;
